package org.computate.tool;

import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.google.gdata.util.common.net.UriEncoder;

public class ComputateTaglib {

	public static String encodeUri(String uri) {
		String result = null;
		
		try {
			if(uri != null) {
				result = UriEncoder.encode(uri, Charset.forName("UTF8"));
			}
		} catch (Exception e) {
		}
		
		return result;
	}

	public static String decodeUri(String uri) {
		String result = null;
		
		try {
			if(uri != null) {
				result = UriEncoder.decode(uri, Charset.forName("UTF8"));
			}
		} catch (Exception e) {
		}
		
		return result;
	}
	
	public static String getRequestUriAndBeyond(HttpServletRequest request) {
		String result = null;
		
		if(request != null) {
			String queryString = request.getQueryString();
			
			result = request.getRequestURI();
			if(!StringUtils.isEmpty(queryString)) {
				result += "?" + queryString;
			}
		}
		
		return result;
	}
	
	public static String addUriParam(String uri, String param, String value) {
		String result = null;
		
		if(uri != null && param != null) {
			String anchor = StringUtils.substringAfter(uri, "#");
			
			result = uri;
			if(!StringUtils.isEmpty(anchor))
				result = StringUtils.substringBefore(result, "#");
			
			if(result.contains("?"))
				result += "&" + encodeUri(param) + "=" + encodeUri(value);
			else
				result += "?" + encodeUri(param) + "=" + encodeUri(value);
			if(!StringUtils.isEmpty(anchor))
				result += anchor;
		}
		
		return result;
	}
	
	public static int toInt(Double d) {
		return d.intValue();
	}
}
